<template>
  <div class="add-data-view">
    <h1>新增数据页面</h1>
    <el-form :model="form" :rules="rules" ref="form" label-width="100px">
      <el-form-item label="描述" prop="id">
        <el-input v-model="form.des"></el-input>
      </el-form-item>
      <el-form-item label="菜单分类" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { addCategory } from '@/api/user'

export default {
  name: 'AddDataView',
  data() {
    return {
      form: {
        des: '', // 描述
        name: '' // 菜单分类
      },
      rules: {
        des: [
          { required: true, message: '请输入描述', trigger: 'blur' } // 描述必填规则
        ],
        name: [
          { required: true, message: '请输入菜单分类', trigger: 'blur' } // 菜单分类必填规则
        ]
      }
    }
  },
  methods: {
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          addCategory(this.form).then(() => {
            this.$message.success('添加成功'); // 添加成功提示
            this.resetForm();
          }).catch(error => {
            this.$message.error('添加失败：' + error.message); // 添加失败提示
          });
        } else {
          return false; // 表单验证失败
        }
      });
    },
    resetForm() {
      this.$refs.form.resetFields(); // 重置表单字段
      this.$router.push('/'); // 返回首页
    }
  }
}
</script>

<style scoped>
.add-data-view {
  padding: 20px;
}
</style>
